<template>
	<view class="chat">
		<!-- 顶部标题 -->
		<!-- 聊天主体 -->
			<!-- 聊天记录 -->
			<!--  -->
		<scroll-view
			id="scrollview"
			ref="scrollView"
			scroll-y="true"
			:scroll-top="scrollTop"
			class="scroll-view chat-body"
			:scroll-with-animation="true"
			:style="{ height: `${windowHeight - inputHeight - 200}rpx` }"
			>
			<view class="official-content" id="scroll-view-content">
					<view class="font text-center" style="margin: 20rpx 0;">{{ System_messages.Message }}</view>
					<view v-for="(item, index) in msgList" :key="index">
						<!-- 时间提示 -->
						<view class="font text-center" v-if="item.payload">{{
							item.payload.text
						}}</view>
						<!-- 自己发的消息 -->
						<view class="item self" v-if="item.userContent != '' && item.userContent != undefined">
							<!-- 文字内容 -->
							<view class="content right">
								{{ item.userContent }}
							</view>
							<!-- 头像 -->
							<image class="avatar" :src="userImage"> </image>
						</view>
						<!-- 机器人发的消息 -->
						<view class="item Ai" v-if="item.botContent != '' && item.botContent != undefined">
							<!-- 头像 -->
							<image class="avatar" :src="Domain_ICON + '/serve.png'"> </image>
							<!-- 文字内容 -->
							<view class="content left">
								{{
									item.botContent
								}}
							</view>
						</view>
			  		</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom">
			<view class="send-msg" style="display: flex; align-items: center">
				<view class="uni-textarea">
					<uni-easyinput type="textarea" v-model="chatMsg" autoHeight class="textarea"></uni-easyinput>
				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	const app = getApp();
	import {
		msgTimeFormat
	} from "@/static/js/common.js";
	import { NowTime} from "@/static/js/DateUtil.js"
	import { log } from "util";
	import {WXAddAction} from "@/api/global.js";
	export default {
		data() {
			return {
				socketTask: null,
				// 确保websocket是打开状态
				is_open_socket: false,
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId: "",
				//发送的消息
				chatMsg: "",
				userImage: app.globalData.memberInfo.Image,
				serveImage: app.globalData.memberInfo.Image,
				msgList: [{
						botContent: "你好啊，我是您的私人客服，请问我有什么可以帮助你的吗？",
						userContent: "",
						time: parseInt(new Date().getTime() / 1000),
						type: "",
					}
				],
				Domain_ICON: app.globalData.Domain_ICON, //全局变量域名
				System_messages : {},
				Service_ID:"",
				scrollViewHeight:0
			};
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			// this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight);
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight;
			},
		},
		onLoad() {
			uni.onKeyboardHeightChange((res) => {
				this.keyboardHeight = this.rpxTopx(res.height);
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			});
			this.msgList = msgTimeFormat(this.msgList, 0, 1);
			this.scrollToBottom();
		},
		onShow() {
			this.connectSocketInit();
		},
		onHide() {
			this.closeSocket();
		},
		unmounted() {
			this.closeSocket();
		},
		onUnload(){
			this.closeSocket();
		},
		 mounted() {
		    // 在页面加载完成后执行
		    // this.getHeight();
			this.scrollToBottom();
		},
		methods: {
			//滚动到底部
			scrollToBottom(){
				const _this = this;
				uni.createSelectorQuery()
				    .select('#scrollview') // 选择要获取高度的元素
					.boundingClientRect((rect) => {
						_this.scrollViewHeight = parseInt(rect.height - 100 - 75 - 75);
					})
					  .exec();
				this.$nextTick(()=>{
					uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res)=>{
						let top = res.height - this.scrollViewHeight ;
						if(top>0){
							this.scrollTop= top + 20;
						}
					}).exec()
				})
			},
			//历史记录
			async aHistory(Service_ID,Messages,App_ID){
				let table = {
					Member_Serves_SerialNumber:'',
					Open_ID:app.globalData.openid,
					Service_ID,
					Messages,
					Message_Time :NowTime(),
					Open_ID_Type: '0',
					Service_ID_Type: '0',
					App_ID,
					Enterprise_Info_SerialNumber : app.globalData.enterprise,
					Row_Status: '0'
           		 };
				const res = await WXAddAction({
					Data:JSON.stringify({member_serves_info: [table]}),
					Open_ID:app.globalData.openid
				})
			},
			// getHeight() {
			// 	 let msglistviewHeight;
			// 	 let scrollviewHeight;
			//       uni.createSelectorQuery()
			//         .select('#msglistview') // 选择要获取高度的元素
			//         .boundingClientRect((rect) => {
			//           console.log('元素高度msglistview：', rect.height);
			// 		  msglistviewHeight = rect.height;
			//         })
			//         .exec();
			// 		//scrollview
			// 		uni.createSelectorQuery()
			// 		  .select('#scrollview') // 选择要获取高度的元素
			// 		  .boundingClientRect((rect) => {
			// 			console.log('元素高度scrollview：', rect.height);
			// 		    scrollviewHeight = rect.height;
			// 		  })
			// 		  .exec();
			// 		 this.scrollTop = Number((msglistviewHeight  - scrollviewHeight))  - 85;
			// },

			focus() {
				this.scrollToBottom();
			},
			blur() {
				this.scrollToBottom();
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth;
				let rpx = (750 / deviceWidth) * Number(px);
				return Math.floor(rpx);
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select(".send-msg").boundingClientRect();
					query.exec((res) => {
						this.bottomHeight = this.rpxTopx(res[0].height);
					});
				}, 10);
			},
			// 滚动至聊天底部
			// scrollToBottom(e) {
			//   setTimeout(() => {
			//     let query = uni.createSelectorQuery().in(this);
			//     query.select("#scrollview").boundingClientRect();
			//     query.select("#msglistview").boundingClientRect();
			// 	log('1',query)
			//     query.exec((res) => {
			//       if (res[1].height > res[0].height) {
			//         this.scrollTop = this.rpxTopx(res[1].height - res[0].height);
			//       }
			//     });
			//   }, 15);
			// },
			// 发送消息
			handleSend() {
				const _this = this;
				//如果消息不为空
				if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
					let obj = {
						botContent: "",
						userContent: this.chatMsg,
						time: parseInt(new Date().getTime() / 1000),
						type: "",
					};
					this.msgList.push(obj);
					this.msgList = msgTimeFormat(this.msgList, 0, 1);
					if (this.is_open_socket && this.chatMsg != "") {
						this.socketTask.send({
							data: JSON.stringify({
								Message: this.chatMsg,
								Time:NowTime()
							}),
							async success() {
								console.log("消息发送成功");
								//存历史记录
								let Service_ID = _this.Service_ID;
								let Messages = _this.chatMsg;
								let App_ID = uni.getStorageSync("App_ID");
								console.log(uni.getStorageSync("App_ID"));
								if (Service_ID) {
									_this.aHistory(Service_ID,Messages,App_ID)
								}
							},
						});
						//存历史记录
					}
					this.chatMsg = "";
				} else {
					uni.showToast({
						title: "不能发空消息哦",
						icon: "error",
					});
				}
				this.scrollToBottom();
			},
			connectSocketInit() {
				const _this = this;
				var a = encodeURI(encodeURI(app.globalData.memberInfo.Nick));
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// url: "wss"+(app.globalData.Domain_Names).+" 01/websocket?userId="+app.globalData.openid,
					url: "wss"+(app.globalData.Domain_Name).slice(5)+"/websocket?userId="+"WeChat;custom;"
					+ app.globalData.openid + ";" + app.globalData.enterprise,
					success(data) {
						console.log("websocket连接成功");
					},
				});
				// // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.is_open_socket = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息

					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log(JSON.parse(res.data));
						this.Service_ID = JSON.parse(res.data).Service;
						if (JSON.parse(res.data).message_type == "system_messages") {
							_this.System_messages = JSON.parse(res.data);
						}else{
							this.msgList.push({
								botContent: JSON.parse(res.data).Message,
								userContent: "",
								time: parseInt(new Date().getTime() / 1000),
								type: "",
							});
						}
					});
				});
				// // 这里仅是事件监听【如果socket关闭了会执行】
				// this.socketTask.onClose(() => {
				// 	console.log("已经被关闭了")
				// })
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.is_open_socket = false;
						console.log("关闭成功", res);
					},
					fail(err) {
						console.log("关闭失败", err);
					},
				});
			},
			clickRequest() {
				if (this.is_open_socket) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					this.socketTask.send({
						data: "请求一次发送一次message",
						async success() {
							console.log("消息发送成功");
						},
					});
				}
			},
		},
	};
</script>
<style lang="scss" scoped>
	$chatContentbgc: #c2dcff;
	$sendBtnbgc: #4f7df5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.scroll-Y {
		height: 300rpx;
	}

	/* 聊天消息 */
	.chat {
		.topTabbar {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			display: flex;
			margin-top: 80rpx;
			justify-content: space-between;

			.icon {
				margin-left: 20rpx;
			}

			.text {
				margin: auto;
				font-size: 16px;
				font-weight: 700;
			}

			.button {
				width: 10%;
				margin: auto 20rpx auto 0rpx;
			}
		}

		.scroll-view {
			// padding: 0 0 190rpx 0;

			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #f6f6f6;
		}

		.chat-body {
			display: flex;
			flex-direction: column;
			padding-top: 23rpx;
			// background-color:skyblue;
			.self {
				justify-content: flex-end;
			}

			.item {
				display: flex;
				padding: 23rpx 30rpx;
				// background-color: greenyellow;

				.right {
					background-color: $chatContentbgc;
				}

				.left {
					background-color: #ffffff;
				}

				// 聊天消息的三角形
				.right::after {
					position: absolute;
					display: inline-block;
					content: "";
					width: 0;
					height: 0;
					left: 100%;
					top: 10px;
					border: 12rpx solid transparent;
					border-left: 12rpx solid $chatContentbgc;
				}

				.left::after {
					position: absolute;
					display: inline-block;
					content: "";
					width: 0;
					height: 0;
					top: 10px;
					right: 100%;
					border: 12rpx solid transparent;
					border-right: 12rpx solid #ffffff;
				}

				.content {
					position: relative;
					max-width: 486rpx;
					border-radius: 8rpx;
					word-wrap: break-word;
					padding: 24rpx 24rpx;
					margin: 0 24rpx;
					border-radius: 5px;
					font-size: 32rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
					line-height: 42rpx;
				}

				.avatar {
					display: flex;
					justify-content: center;
					width: 78rpx;
					height: 78rpx;
					border-radius: 50rpx;
					overflow: hidden;

					image {
						align-self: center;
					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #f4f5f7;
			transition: all 0.1s ease;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				width: 537rpx;
				max-height: 500rpx;
				background: #f1f1f1;
				border-radius: 40rpx;
				font-size: 32rpx;
				font-family: PingFang SC;
				color: #333333;
				line-height: 74rpx;
				text-indent: 30rpx;

				//   margin: 0 0 20rpx 0;
				/deep/ .uni-easyinput__content-textarea {
					min-height: 60rpx;
					display: flex;
					align-items: center;
					padding: 0;
				}

				/dee/ .input-padding {
					padding: 0;
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				//   margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 120rpx;
				height: 84rpx;
				background: #ed5a65;
				//   border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #ffffff;
				line-height: 28rpx;
			}
		}
	}
</style>